package com.shujia.flink.dx

import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.table.api.EnvironmentSettings
import org.apache.flink.table.api.bridge.scala.StreamTableEnvironment

object Demo3CityFlowOnSql {
  def main(args: Array[String]): Unit = {
    //创建flink 环境
    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //设置table 环境的一些参数
    val bsSettings: EnvironmentSettings = EnvironmentSettings.newInstance()
      .useBlinkPlanner() //使用blikc计划器
      .inStreamingMode() //流模式
      .build()

    // 创建flink  table 环境
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)

    /**
      * 1、读取kafka中电信用户位置数据
      *
      */

    bsTableEnv.executeSql(
      """
        |
        |CREATE TABLE dianxin (
        |mdn STRING,
        |grid STRING,
        |city STRING,
        |county STRING,
        |tTime INT,
        |start_time STRING,
        |end_time STRING,
        |`date` STRING
        |) WITH (
        | 'connector' = 'kafka',
        | 'topic' = 'dianxin1',
        | 'properties.bootstrap.servers' = 'master:9092,node1:9092,node2:9092',
        | 'properties.group.id' = 'testGroup',
        | 'format' = 'csv',
        | 'scan.startup.mode' = 'earliest-offset',
        | 'csv.ignore-parse-errors' = 'true'
        |)
        |
      """.stripMargin)

    bsTableEnv.executeSql(
      """
        |CREATE TABLE print_table(
        |city STRING,
        |num BIGINT
        |)
        |WITH ('connector' = 'print')
        |
      """.stripMargin)

    bsTableEnv.executeSql(
      """
        |CREATE TABLE city_num (
        |  city STRING,
        |  num BIGINT,
        |  PRIMARY KEY (city) NOT ENFORCED
        |) WITH (
        |   'connector' = 'jdbc',
        |   'url' = 'jdbc:mysql://master:3306/bigdata',
        |   'table-name' = 'city_count',
        |   'username' = 'root',
        |   'password' = '123456'
        |)
        |
      """.stripMargin)


    bsTableEnv.executeSql(
      """
        |insert into city_num
        |select
        |city,
        |count(distinct mdn) as num
        |from dianxin
        |group by city
        |
      """.stripMargin)

    /**
      *
      * flink run -m yarn-cluster  -yjm 1024m -ytm 1096m -c com.shujia.flink.dx.Demo3CityFlowOnSql flink-1.0.jar
      */
  }

}
